package com.talkweb.reader.maintab;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.talkweb.baselibrary.base.BaseFraction;
import com.talkweb.baselibrary.utils.LogUtil;
import com.talkweb.baselibrary.utils.StringUtils;
import com.talkweb.reader.ResourceTable;
import com.talkweb.reader.maintab.adapter.HomeAdapter;
import com.talkweb.reader.maintab.adapter.OnHomeAdapterClickListener;
import com.talkweb.reader.maintab.bean.HomeDesignBean;
import com.talkweb.reader.maintab.bean.SearchBookBean;
import com.talkweb.reader.maintab.bean.SourceListContent;
import com.talkweb.reader.maintab.detail.BookDetailAbility;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.render.PixelMapShader;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class MainFraction extends BaseFraction implements OnHomeAdapterClickListener {

    private ListContainer listContainer;
    private HomeAdapter homeAdapter;
    List<String> carouselImages = new ArrayList<>();
    List<HomeDesignBean> list = new ArrayList<>();
    List<SourceListContent> recommendList = new ArrayList<>();

    @Override
    protected int getUIContent() {
        return ResourceTable.Layout_fraction_main;
    }

    @Override
    protected void initializeComponent(Component component) {
        listContainer = (ListContainer) component.findComponentById(
                ResourceTable.Id_listContainer);
        initData();
    }

    private void initData() {
        homeAdapter = new HomeAdapter(getFractionAbility(), list, carouselImages, recommendList,this);
        listContainer.setItemProvider(homeAdapter);
        EasyHttp.get("/appview/homeViewData")
                .baseUrl("http://aimanpin.com")
                .readTimeOut(30 * 1000)//局部定义读超时
                .writeTimeOut(30 * 1000)
                .connectTimeout(30 * 1000)
                .timeStamp(true)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        LogUtil.e("data===",e.getMessage());

                    }

                    @Override
                    public void onSuccess(String response) {
                        if (response != null) {
                            LogUtil.e("data===",response);
                            parseData(response);
                        }
                    }
                });
    }

    private void parseData(String response){
        JSONObject jsonObject = JSON.parseObject(response);
        JSONObject data = (JSONObject) jsonObject.get("data");
        if (data != null) {
            String carouselJson = JSON.toJSONString(data.get("carouselImages"));
            String homebookJson = JSON.toJSONString(data.get("homeBook"));
            String recommendJson = JSON.toJSONString(data.get("recommend"));
            if (!StringUtils.isEmpty(homebookJson) && !StringUtils.isEmpty(recommendJson)
                    && !StringUtils.isEmpty(carouselJson)) {
                carouselImages = JSON.parseArray(carouselJson, String.class);
                list = JSON.parseArray(homebookJson, HomeDesignBean.class);
                recommendList = JSON.parseArray(recommendJson, SourceListContent.class);
                if (list != null && list.size() > 0
                        && carouselImages != null && carouselImages.size() > 0
                        && recommendList != null && recommendList.size() == 3) {

                   homeAdapter.setNewData(list,carouselImages,recommendList);

                } else {
                    try {
                        RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry("resources/rawfile/localhome.json");
                        Resource resource = rawFileEntry.openRawFile();
                        ByteArrayOutputStream boa=new ByteArrayOutputStream();
                        int len=0;
                        byte[] buffer=new byte[1024];
                        while((len=resource.read(buffer))!=-1){
                            boa.write(buffer,0,len);
                        }
                        resource.close();
                        boa.close();
                        byte[] result=boa.toByteArray();
                        String res = new String(result);
                        parseData(res);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    @Override
    public void onItemClickListener(Component component) {
        int id = component.getId();
        switch (id) {
            case ResourceTable.Id_dongman_cit:

                break;
            case ResourceTable.Id_mingxinpian_cit:

                break;
            case ResourceTable.Id_shujia_cit:

                break;
            case ResourceTable.Id_guangchang_cit:

                break;
            case ResourceTable.Id_serch_sl:

                break;
            default:
                break;
        }
    }

    @Override
    public void onLayoutClickListener(Component component, SourceListContent sourceListContent) {
        SearchBookBean searchBookBean = new SearchBookBean();
        searchBookBean.setName(sourceListContent.getName());
        searchBookBean.setCoverUrl(sourceListContent.getCoverUrl());
        searchBookBean.setNoteUrl(sourceListContent.getNoteUrl());
        searchBookBean.setAuthor(sourceListContent.getAuthor());
        searchBookBean.setDesc(sourceListContent.getBookdesc());
        searchBookBean.setOrigin(sourceListContent.getOrigin());
        searchBookBean.setKind(sourceListContent.getKind());
        searchBookBean.setTag(sourceListContent.getTag());
        searchBookBean.setAdd(false);
        searchBookBean.setWords(0);

        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getFractionAbility().getBundleName())
                .withAbilityName(BookDetailAbility.class.getName())
                .build();
        intent.setParam("searchBookBean", searchBookBean);
        intent.setOperation(operation);
        startAbility(intent);
        showToast(getFractionAbility(),sourceListContent.getName());
    }

    @Override
    public void onContentChangeClickListener(int mContentPosition, String kinds) {

    }
}
